package cn.tedu.filter;

import cn.tedu.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.util.HTTPRequestUtils;
import com.sun.scenario.effect.FilterContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * zuul过滤器
 */

@Component
public class zuulFilter extends ZuulFilter {
    //前置,后置,陆游,错误处理
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //顺序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //针对当前请求是否需要执行过滤
    @Override
    public boolean shouldFilter() {
        /**
         * 如需请求商品进行过滤'
         * 其他则跳过过滤;
         */
       RequestContext cct =  RequestContext.getCurrentContext();
        String serviceId = (String) cct.get(FilterConstants.SERVICE_ID_KEY);
        if (serviceId.equalsIgnoreCase("item-service")){
            return true;
        }
        return false;
    }
    //判断权限,
    @Override
    public Object run() throws ZuulException {
        //获取request对象
        RequestContext cct =  RequestContext.getCurrentContext();
        HttpServletRequest request = cct.getRequest();
        //接受token参数
        String token = request.getParameter("token");
        //判断是否有token
        if(StringUtils.isBlank(token)){
            //添加头信息
            //设置状态信息
            cct.addZuulResponseHeader("CONTEXT-TYPE","item-service");
            cct.setResponseStatusCode(JsonResult.NOT_LOGIN);
            cct.setResponseBody(JsonResult
                   .err()
                   .code(JsonResult.NOT_LOGIN)
                   .msg("not login").toString());
        }
        return null;
    }
}
